using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Traceability.Products.Queries;

/// <summary>
/// 查询工艺步骤以及其所有的工步的过程数据命令。
/// </summary>
/// <param name="StepExecutionId">工艺步骤执行记录 Id</param>
public sealed record GetStepProcessDataQuery(long StepExecutionId) : IRequest<IResult<ProdProcessDataDto>>;

internal sealed class GetStepProcessDataQueryHandler(
    IRepository<ProdStepExecution> stepExecutionRepo,
    IRepository<ProdStepTaskExecution> stepTaskExecutionRepo) : IRequestHandler<GetStepProcessDataQuery, IResult<ProdProcessDataDto>>
{
    public async Task<IResult<ProdProcessDataDto>> Handle(GetStepProcessDataQuery request, CancellationToken cancellationToken)
    {
        // 注：若使用分区表或是分表，不要用导航查询，过程数据应该单独查询且需要带上日期查询。

        var stepExecution = await stepExecutionRepo.AsQueryable()
            .Includes(m => m.Data)
            .Where(m => m.Id == request.StepExecutionId)
            .FirstOrDefaultAsync(cancellationToken);
        if (stepExecution == null)
        {
            return Result.From(new ProdProcessDataDto());
        }

        var stepTaskExecution = await stepTaskExecutionRepo.AsQueryable()
            .Includes(m => m.Data)
            .Where(m => m.InboundId == stepExecution.InboundId && m.StepId == stepExecution.StepId)
            .ToListAsync(cancellationToken);
        return Result.From(new ProdProcessDataDto()
        {
            StepExecution = stepExecution.Adapt<ProdStepExecutionDto>(),
            StepTaskExecutions = stepTaskExecution.Adapt<List<ProdStepTaskExecutionDto>>(),
        });
    }
}
